home *** CD-ROM | disk | FTP | other *** search
- Path: unix.sri.com!usenet
- From: mklenk@updike.sri.com (Mark Klenk)
- Newsgroups: comp.std.c
- Subject: Re: memcpy
- Date: 19 Jan 1996 16:10:31 GMT
- Organization: SRI International
- Message-ID: <4dofpn$fk9@unix.sri.com>
- References: <4dn0gu$itc@mirv.unsw.edu.au>
- Reply-To: mklenk@updike.sri.com
- NNTP-Posting-Host: 204.75.161.40
-
- Geoff Wong wrote:
- >
- >Can memcpy cope with very complex objects?
-
- I think what you're asking is whether memcpy() will perform
- what is called a "deep" copy. No, it will not. memcpy()
- simply copies a block of memory (contiguous bytes) from one
- location to another. If you use it to copy an object that
- contains pointers, the copy of it will contain those same
- pointers, not new pointers to copies of what the original
- ones pointed to. This is called a "shallow" copy, and is
- all that memcpy()/memmove() can do.
-
- If you want to implement a deep copy, you'll have to write
- the routine yourself, something like:
-
- typedef struct {
- int a, b;
- char * bar;
- } Foo;
-
- Foo * FooClone(Foo const * original)
- {
- Foo * foo;
-
- foo = (Foo *)malloc(sizeof(Foo));
- if (NULL != foo) {
- size_t size = strlen(original->bar) + 1;
- foo->a = original->a;
- foo->b = original->b;
- foo->bar = (char *)malloc(size);
- if (NULL == foo->bar) {
- free(foo);
- foo = NULL;
- } else {
- memcpy(foo->bar, original->bar, size);
- }
- }
-
- return foo;
- }
-
- To sidetrack a little, this is what the copy constructor in
- C++ is often used for.
-
- ---
-
- mklenk@coronacorp.com (Mark Klenk)
-
-
-
-